/*
Using the time built-in command of the shell, try timing the operation of the
program in Listing 4-1 ( copy.c ) on your system.
a) Experiment with different file and buffer sizes. You can set the buffer size
using the –DBUF_SIZE=nbytes option when compiling the program.
b) Modify the open() system call to include the O_SYNC flag. How much differ-
ence does this make to the speed for various buffer sizes?
c)
Try performing these timing tests on a range of file systems (e.g., ext3, XFS,
Btrfs, and JFS). Are the results similar? Are the trends the same when going
from small to large buffer sizes?
 */

/*
Results:
200 bytes - 1,39s user 3,24s system 99% cpu 4,632 total
512 bytes - 0,48s user 1,43s system 99% cpu 1,926 total
4096 bytes - 0,09s user 0,35s system 99% cpu 0,444 total
8192 bytes - 0,03s user 0,35s system 99% cpu 0,376 total
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#ifndef BUFFER_SIZE
#define BUFFER_SIZE 200
#endif

int
main(int argc, char *argv[])
{
  int input_fd, output_fd, open_flags;
  mode_t file_perms;
  if (argc != 3 || strcmp(argv[1], "--help") == 0)
    {
      puts("wrong argument");
      exit(EXIT_FAILURE);
    }

  input_fd = open(argv[1], O_RDONLY);
  if (input_fd == -1) exit(EXIT_FAILURE);
  open_flags = O_CREAT|O_WRONLY|O_TRUNC|O_SYNC;
  file_perms = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH;
  output_fd = open(argv[2], open_flags, file_perms);
  if (output_fd == -1) exit(EXIT_FAILURE);
  ssize_t num_read;
  char buffer[BUFFER_SIZE];
  while ((num_read = read(input_fd, buffer, BUFFER_SIZE)) > 0)
    if (write(output_fd, buffer, num_read) != num_read)
      exit(EXIT_FAILURE);
  if (num_read == -1) exit(EXIT_FAILURE);
  close(output_fd);
  close(input_fd);

  return EXIT_SUCCESS;
}
